package com.block.source.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.LogFactory;
import com.block.db.entity.*;
import com.block.db.mapper.AddressInfoMapper;
import com.block.db.mapper.MemberBaseInfoMapper;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.db.mapper.SourceMemberDataInfoTempMapper;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceMemberDataInfoService;
import com.block.source.service.ISourceMemberDataInfoTempService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.block.source.service.ISourcePushResultInfoService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.yaml.snakeyaml.events.Event;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;

/**
 * <p>
 * 线索用户资质信息表 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-12-27
 */
@Service
public class SourceMemberDataInfoTempServiceImpl extends ServiceImpl<SourceMemberDataInfoTempMapper, SourceMemberDataInfoTemp> implements ISourceMemberDataInfoTempService {


    private static final Logger log = LogFactory.getSourceLog();

    @Autowired
    NotifyExceptionService notifyExceptionService;
    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    AddressInfoMapper addressInfoMapper;

    @Resource
    MemberBaseInfoMapper memberBaseInfoMapper;
    @Resource
    MemberSourceInfoMapper memberSourceInfoMapper;
    @Autowired
    ISourceMemberDataInfoService sourceMemberDataInfoService;
    @Autowired
    ISourcePushResultInfoService sourcePushResultInfoService;

    /**
     * 撞库保存 用户资质信息
     * @param userDataParam
     * @param channelBaseInfo
     * @param applicationInfo
     * @return
     */
    @Override
    public ResultInfoVO saveMemberData(UserDataParam userDataParam, ChannelBaseInfo channelBaseInfo, ApplicationInfo applicationInfo) {

        AddressInfo addressInfo = addressInfoService.getAddressInfoByCityCode(userDataParam.getCityCode());
        if (ObjectUtil.isEmpty(addressInfo)){
            String message = StrUtil.format("【city】{}【cityCode】{}【channelCode】{}", userDataParam.getCity(), userDataParam.getCityCode(), channelBaseInfo.getChannelCode());
            notifyExceptionService.notifyNoticeInfo("SOURCE_CHECK_CITY_ERROR", "线索撞库城市编码不支持", message, null);
            return ResultInfoVO.error("不支持的城市信息");
        }

        //APIB/APIS如果撞库没有姓名，传默认
        if (StringUtils.isEmpty(userDataParam.getRealName())){
            userDataParam.setRealName("默认");
        }

        SourceMemberDataInfoTemp memberDataInfo  = new SourceMemberDataInfoTemp();
        BeanUtil.copyProperties(userDataParam, memberDataInfo, true);
        memberDataInfo.setDateInfo(LocalDate.now().toString());
        memberDataInfo.setChannelCode(channelBaseInfo.getChannelCode());
        memberDataInfo.setChannelName(channelBaseInfo.getChannelName());
        memberDataInfo.setAppCode(applicationInfo.getAppCode());
        memberDataInfo.setAppName(applicationInfo.getAppName());

        boolean save = this.save(memberDataInfo);
        if (save){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dataId", String.valueOf(memberDataInfo.getId()));
            jsonObject.put("dataInfo", memberDataInfo);

            return ResultInfoVO.success(jsonObject);
        }
        return ResultInfoVO.error("信息入库失败");
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public ResultInfoVO updateDataInfo(SourceMemberDataInfoTemp memberDataInfoTemp, UserDataParam userDataParam,
                                       SourcePushResultInfo pushResultInfo){

        SourceMemberDataInfoTemp updateEntity = new SourceMemberDataInfoTemp();
        updateEntity.setId(memberDataInfoTemp.getId());
        updateEntity.setMobile(userDataParam.getMobile());
        updateEntity.setRealName(userDataParam.getRealName());
        updateEntity.setRealName(userDataParam.getRealName());
        this.updateById(updateEntity);

        memberDataInfoTemp.setMobile(userDataParam.getMobile());
        memberDataInfoTemp.setRealName(userDataParam.getRealName());

        // 生成基本用户信息
        MemberBaseInfo memberBaseInfo = this.saveMemberBaseInfo(memberDataInfoTemp, userDataParam);
        if (ObjectUtil.isEmpty(memberBaseInfo)){
            log.info("【线索注册】保存用户信息失败base【tempDataId】{}【userDataParam】{}", memberDataInfoTemp.getId(), JSON.toJSONString(userDataParam));
            return ResultInfoVO.error("保存注册信息失败base");
        }

        // 生成用户资质信息
        MemberSourceInfo memberSourceInfo = this.saveMemberSourceInfo(memberDataInfoTemp, userDataParam, memberBaseInfo);
        if (ObjectUtil.hasEmpty(memberBaseInfo, memberSourceInfo)){
            log.info("【线索注册】保存用户信息失败source【tempDataId】{}【userDataParam】{}", memberDataInfoTemp.getId(), JSON.toJSONString(userDataParam));
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultInfoVO.error("保存注册信息失败source");
        }

        // 生成记录信息
        SourceMemberDataInfo sourceMemberDataInfo = sourceMemberDataInfoService.saveMemberData(memberDataInfoTemp, userDataParam, memberBaseInfo);
//        if (ObjectUtil.isNotEmpty(sourceMemberDataInfo)){
//            sourceMemberDataInfoService.updateIpInfo(sourceMemberDataInfo.getId());
//        }

        SourcePushResultInfo updateResult = new SourcePushResultInfo();
        updateResult.setId(pushResultInfo.getId());
        updateResult.setUid(memberBaseInfo.getUid());
//        updateResult.setRegisterIp(userDataParam.getRequestIp());
        sourcePushResultInfoService.updateById(updateResult);

        JSONObject returnObjcet = new JSONObject();
        returnObjcet.put("memberSourceInfo", memberSourceInfo);
        returnObjcet.put("memberBaseInfo", memberBaseInfo);

        return ResultInfoVO.success(returnObjcet);
    }

    private MemberSourceInfo saveMemberSourceInfo(SourceMemberDataInfoTemp memberDataInfoTemp, UserDataParam userDataParam, MemberBaseInfo memberBaseInfo) {

        MemberSourceInfo exitInfo = memberSourceInfoMapper.selectById(memberBaseInfo.getUid());
        if (ObjectUtil.isNotEmpty(exitInfo)){
            // 资质信息不为空
            memberSourceInfoMapper.deleteById(memberBaseInfo.getUid());
        }

        MemberSourceInfo memberSourceInfo = new MemberSourceInfo();
        BeanUtil.copyProperties(memberDataInfoTemp, memberSourceInfo, true);
        memberSourceInfo.setUid(memberBaseInfo.getUid());
        memberSourceInfo.setMobile(userDataParam.getMobile());
        memberSourceInfo.setIdcard(userDataParam.getIdCard());
        memberSourceInfo.setDateInfo(LocalDate.now().toString());
        memberSourceInfo.setReqIp(userDataParam.getUserIp());
        memberSourceInfo.setMobileMd5(SecureUtil.md5(userDataParam.getMobile()));
        int insert = memberSourceInfoMapper.insert(memberSourceInfo);

        if (insert > 0){
            return memberSourceInfoMapper.selectById(memberSourceInfo.getUid());
        }
        return null;
    }

    public MemberBaseInfo saveMemberBaseInfo(SourceMemberDataInfoTemp memberDataInfoTemp, UserDataParam userDataParam) {

        MemberBaseInfo memberBaseInfo = memberBaseInfoMapper.getBaseUserInfoByPhoneLock(userDataParam.getMobile());
        int action = 0;
        if (ObjectUtil.isNotEmpty(memberBaseInfo)){
            // 更新用户信息
            MemberBaseInfo updateEntity = new MemberBaseInfo();
            updateEntity.setUid(memberBaseInfo.getUid());
            updateEntity.setSourceFlag(1);
            updateEntity.setUpdateTime(LocalDateTime.now());
            action = memberBaseInfoMapper.updateById(updateEntity);
        }else{
            // 生成用户信息
            memberBaseInfo = new MemberBaseInfo();
            memberBaseInfo.setDateInfo(LocalDate.now().toString());
            memberBaseInfo.setMobile(userDataParam.getMobile());
            memberBaseInfo.setMobileMd5(memberDataInfoTemp.getMobileMd5());
            memberBaseInfo.setChannelCode(memberDataInfoTemp.getChannelCode());
            memberBaseInfo.setChannelName(memberDataInfoTemp.getChannelName());
            memberBaseInfo.setRegAppCode(memberDataInfoTemp.getAppCode());
            memberBaseInfo.setUsername(memberDataInfoTemp.getRealName());
            memberBaseInfo.setSourceFlag(1);
            memberBaseInfo.setAuthFlag(1);
            memberBaseInfo.setRegType(5);
            memberBaseInfo.setRegReqIp(memberDataInfoTemp.getUserIp());
            memberBaseInfo.setMobileMask(memberDataInfoTemp.getMobileMask());
            action = memberBaseInfoMapper.insert(memberBaseInfo);
        }

        if (action > 0) {
            return memberBaseInfoMapper.selectById(memberBaseInfo.getUid());
        }
        return null;
    }





}
